//
//  CustomSortButtonView.m
//  wtshoppingcite
//
//  Created by Baojia-LC on 14/11/21.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "CustomSortButtonView.h"

@implementation CustomSortButtonView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)initWithItemNames:(NSArray *)itemNames itemImages:(NSArray*)images;
{
    UIImageView * line = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.frame) - 3, CGRectGetWidth(self.frame), 1)];
    line.backgroundColor = COLOR_RGBA(220, 220, 220, 1);
    [self addSubview:line];
    
    int count = [itemNames count];
    float width = CGRectGetWidth(self.frame) / count;
    float height = CGRectGetHeight(self.frame);
    
    for (int i = 0; i < count; i ++) {
        NSString* title = [itemNames objectAtIndex:i];
        UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(width * i, 0, width, height - 3)];
        [btn setTitle:title forState:UIControlStateNormal];
        btn.tag = 1000 + i;
        [btn setTitleColor:MAIN_BLACK_COLOR forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
        [btn setTitleColor:MAIN_BLUE_COLOR forState:UIControlStateSelected];
        [btn setImage:[UIImage imageNamed:[images objectAtIndex:i]] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        
//        CGSize titleSize = [title getSizeOfStringFontSize:14 constroSize:CGSizeMake(150, MAXFLOAT)];
        [btn setImageEdgeInsets:UIEdgeInsetsMake(0, -15, 0, 0)];
        [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        
        if (i < count - 1) {
            UIView *seperate = [[UIView alloc]initWithFrame:CGRectMake(btn.right, btn.top, 1, btn.height -10)];
            seperate.backgroundColor = COLOR_RGB(222, 222, 222);
            [self addSubview:seperate];
        }
    }
}

-(void)setItemNames:(NSArray*)itemNames{
    
    int count = [itemNames count];
    for (int i = 0; i < count; i ++) {
        UIButton* btn = (UIButton*)[self viewWithTag:1000+i];
        [btn setTitle:itemNames[i] forState:UIControlStateNormal];
    }
}

- (void)btnPressed:(UIButton *)sender
{
    int index = sender.tag - 1000;
    if (self.delegate && [self.delegate respondsToSelector:@selector(btnPressed:)]) {
        [self.delegate btnPressed:index];
    }
}

@end
